package com.itheima.controller;

import com.itheima.pojo.Feedback;
import com.itheima.pojo.User;
import com.itheima.service.FeedbackService;
import com.itheima.service.UserService;
import com.itheima.utils.CookieUtils;
import com.itheima.utils.Result;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/oauth")
public class OauthController {

    @Value("${sign}")
    private String sign;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private FeedbackService feedbackService;

    @PostMapping("/updateUserPwd")
    public Result updateUserPwd(@RequestParam String oldPwd, @RequestParam String newPwd) {
        Integer count = userService.updatePwd("22222", oldPwd, newPwd);
        if (count == 1) {
            return new Result("success", "修改成功");
        } else {
            return new Result("error", "修改失败");
        }
    }

    //提交反馈
    @PostMapping("/addFeedback")
    public Result addFeedback(@RequestBody Map<String, Object> feedbackVO) {
        feedbackService.add(feedbackVO);
        return new Result("success", "添加成功");
    }

    //用户编辑信息
    @PostMapping("/editUser")
    public Result editUser(@RequestBody Map<String, Object> userVO) {
        userService.editUser(userVO);
        return new Result("success", "操作成功");
    }

    //用户编辑信息
    @GetMapping("/getFeedbackList")
    public Result getFeedbackList() {
        List<Feedback> feedbackList = feedbackService.findByUserUid("22222");
        return new Result("success", feedbackList);
    }

    //获取用户信息
    @GetMapping("/verify/{accessToken}")
    public Result verify(@PathVariable("accessToken") String accessToken) {
        if (StringUtils.isEmpty(accessToken)) {
            throw new RuntimeException("没有携带token");
        }
        //验证token
        Claims claims = Jwts.parser().setSigningKey(sign).parseClaimsJws(accessToken).getBody();
        //获得用户uid
        String uid = claims.getId();
        //查询用户信息
        User user = userService.findById(uid);
        return new Result("success", user);
    }

    //退出登录
    @PostMapping("/delete/{accessToken}")
    public Result delete(@PathVariable("accessToken") String accessToken, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("token")){
                CookieUtils.deleteCookie(cookie.getName());
            }
        }
        return new Result("success", "退出成功");
    }
}
